package Utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import java.sql.Statement;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/*
*  Druid连接池的工具类
* */
public class JDBCUtils {
    // 定义成员变量DataSource
    private static DataSource ds;

    static {
        try {
            //加载配置文件
            Properties aa = new Properties();
            aa.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //获取DataSource
            ds = DruidDataSourceFactory.createDataSource(aa);
        } catch (IOException e) {
                e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        //获取连接对象的操作
      public static Connection getConnection() throws SQLException {
        return ds.getConnection();
      }

      // 归还资源的方法  在连接池当中close方法不是释放资源,而是讲连接对象归还到连接池当中
    public static void close(Statement stmt,Connection conn){
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }
    public static void close(Statement stmt, ResultSet rs, Connection conn){
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

    //  获取连接池的方法
     public static DataSource getDataSource(){

        return ds;
     }

}
